package com.handpay.zztong.hp.base.model.base;


import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.NetEngineListener;
import com.handpay.framework.SSLCustomSocketFactory;
import com.handpay.framework.fastjson.FastJsonHelper;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.BaseActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.activity.WelcomeActivity;

import org.apache.http.HttpStatus;

import java.io.InputStream;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/**
 * Created by lyang on 2017/3/14.
 */

abstract public class BaseModel implements NetEngineListener {

    protected enum DATA_TYPE {
        DATA_TYPE_JSON,
        DATA_TYPE_LUA
    }

    protected DATA_TYPE data_type = DATA_TYPE.DATA_TYPE_JSON;
    protected ZZTongActivity mActivity;


    /**
     * 默认做网络检查，并且显示加载中的对话框
     *
     * @param activity 接受回调的Activity
     * @param action   标示哪个服务
     * @param params   该服务的参数
     * @return 返回为true, 表示发出网络请求
     */
    public boolean doPost(final ZZTongActivity activity, final String action, final Hashtable<String, String> params) {
        return doPost(activity, action, params, true);
    }

    /**
     * 默认做网络是否打开的检查
     *
     * @param activity    接受回调的Activity
     * @param action      标示哪个服务
     * @param params      该服务的参数
     * @param showLoading 请求该访问的时候，是否显示对话框
     * @return 返回为true, 表示发出网络请求
     */
    public boolean doPost(final ZZTongActivity activity, final String action, final Hashtable<String, String> params, boolean showLoading) {
        return doPost(activity, action, params, true, showLoading);
    }

    /**
     * 请求网络访问
     *
     * @param checkNet    做网络请求之前是否，检查网络
     * @param activity    接受回调的Activity
     * @param action      标示哪个服务
     * @param params      该服务的参数
     * @param showLoading 请求该访问的时候，是否显示对话框
     * @return 返回为true, 表示发出网络请求
     */
    protected boolean doPost(final ZZTongActivity activity, final String action, final Hashtable<String, String> params, boolean checkNet, boolean showLoading) {
        mActivity = activity;
        if (checkNet && activity.checkNetAndAlert(activity)) {
            return false;
        }
        HPLog.i(HPLog.FDL_TAG, "Action:" + action + " ShowLoading:" + showLoading);
        if (showLoading) {
            activity.showProgressDialog(activity, activity.getString(R.string.pleasewait));
        }
        HttpSFTConnector.doVolleyPost(this, action, params, checkNet, -1);
        return true;
    }


    protected boolean doPost(final Context context, final String action, final Hashtable<String, String> params) {
//        if (checkNet && activity.checkNetAndAlert(activity)) {
//            return false;
//        }
//        if (showLoading) {
//            activity.showProgressDialog(activity, activity.getString(R.string.pleasewait));
//        } else {
//            HPLog.i(HPLog.FDL_TAG, "Action:" + action + "showLoading:" + showLoading);
//        }
        HttpSFTConnector.doVolleyPost(this, action, params, true, -1);
        return true;
    }

    @Override
    final public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        if (BaseActivity.mProgressDialog != null && BaseActivity.mProgressDialog.isShowing()) {
            BaseActivity.mProgressDialog.dismiss();
            BaseActivity.mProgressDialog = null;
        }
        int respCode = (Integer) resp.get(HttpEngine.Key_RespCode);
        String errMsg = (String) resp.get(HttpEngine.Key_RespErrMsg);
        if (respCode == HttpStatus.SC_REQUEST_TIMEOUT) {
            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.hint_timer_out), errMsg, false, null);
            return;
        } else if (respCode == HttpStatus.SC_NOT_FOUND) {
            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.hint_conn_err), errMsg, false, null);
            return;
        } else if (respCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.hint_server_error), errMsg, false, null);
            return;
        } else if (respCode == HttpStatus.SC_UNAUTHORIZED) {
            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.hint_author_error), errMsg, false, null);
            return;
        }
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        netResponse(action, data);
    }

    @Override
    public void callbackJsonNetResponse(String action, ResponseBean resp, boolean showAlert) {

    }

    public boolean netResponse(String action, byte data[]) {
        return netResponse(action, data, null);
    }

    /**
     * 关于S080退出应用问题，杨说暂时先判断instanceof来区分
     * @param action
     * @param data
     * @param clickListener
     * @return
     */
    public boolean netResponse(String action, byte data[], DialogInterface.OnClickListener clickListener) {
        try {
            String result = new String(data, "UTF-8");
            if (data_type == DATA_TYPE.DATA_TYPE_JSON) {
                ResponseBean respBean = FastJsonHelper.getObject(result, ResponseBean.class);
                if (!TextUtils.isEmpty(respBean.responseCode)) {
                    if (respBean.getResponseCode() != null && respBean.getErrMessage() != null) {

                        DialogInterface.OnClickListener exitlogin = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.exitAccount();
                                dialog.dismiss();
                            }
                        };
                        DialogInterface.OnClickListener exit_app = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.exitapp();
                                dialog.dismiss();
                            }
                        };
                        if (respBean.getResponseCode().equals("S080")) {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), respBean.getErrMessage(), false, (mActivity!=null&&mActivity instanceof WelcomeActivity)?exit_app:clickListener);
                            return true;
                        } else if (respBean.getResponseCode().equals("99")) {
                            HPLog.i(HPLog.YL_TAG,"下线通知-----------");
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.offline_notify_txt), respBean.getErrMessage(), false, exitlogin);
                            return true;
                        } else if (respBean.getResponseCode().equals("999")) {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.offline_notify_txt), respBean.getErrMessage(), false, mActivity.getString(R.string.tv_exit), exit_app, mActivity.getString(R.string.tv_relogin), exitlogin);
                            return true;
                        }
                        if (clickListener != null) {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), respBean.getErrMessage(), false, clickListener);
                        } else {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), respBean.getErrMessage());
                        }
                        return true;
                    }
                }
            } else {
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, true);
                int responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));
                if (responseCode != 0) {
                    String errMessage = CommonUtils.objectToString(luaTable.rawget("errMessage"));
                    if (errMessage != null) {
                        if (clickListener != null) {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), errMessage, true, clickListener);
                        } else {
                            mActivity.showAlertDialog(mActivity, mActivity.getString(R.string.tip), errMessage);
                        }
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }


}
